import uuid
from PIL import Image
import os
import simplejson
from django.http.response import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from settings import config
import time


def uploadfile(fileObj, file_type='pic'):
    """ 一个公用的上传文件的处理 """
    resp = ''
    if fileObj:
        filename = fileObj.name.decode('utf-8', 'ignore')
        fileExt = filename.split('.')[1]
        file_name = str(uuid.uuid1())
        subfolder = time.strftime("%Y%m")
        if not os.path.exists(config.MEDIA_ROOT[0] + subfolder):
            os.makedirs(config.MEDIA_ROOT[0] + subfolder)
        path = str(subfolder + '/' + file_name + '.' + fileExt)

        if fileExt.lower() in (
                'jpg', 'jpeg', 'bmp', 'gif', 'png', "rar", "doc", "docx", "zip", "pdf", "txt", "swf", "wmv"):

            phisypath = config.MEDIA_ROOT[0] + path
            destination = open(phisypath, 'wb+')
            for chunk in fileObj.chunks():
                destination.write(chunk)
            destination.close()

            if file_type == 'pic':
                if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png'):
                    im = Image.open(phisypath)
                    im.thumbnail((720, 720))
                    im.save(phisypath)

            real_url = '/static/upload/' + subfolder + '/' + file_name + '.' + fileExt
            resp = "{'original':'%s','url':'%s','title':'%s','state':'%s'}" % (
                filename, real_url, 'source_file_tile', 'SUCCESS')
    return resp


@csrf_exempt
def ueditor_index(request):
    action = request.GET.get('action', '')
    if action == 'config':
        setting = config.UEDITER_SETTING
        return HttpResponse(simplejson.dumps(setting), content_type='text/html; charset=utf-8')
    elif action == 'uploadfile':
        return HttpResponse(ueditor_uploadfile(request))
    elif action == 'uploadimage':
        return HttpResponse(ueditor_uploadimage(request))
    else:
        return HttpResponseBadRequest()


def format_file_name(name):
    '''
    去掉名称中的url关键字
    '''
    URL_KEY_WORDS = ['#', '?', '/', '&', '.', '%']
    for key in URL_KEY_WORDS:
        name_list = name.split(key)
        name = ''.join(name_list)
    return name


def upload_file(file_obj, file_type='pic'):
    if file_obj:
        filename = file_obj.name
        # filename = file_obj.name.decode('utf-8', 'ignore')
        filename_list = filename.split('.')
        file_postfix = filename_list[-1]  # 后缀
        # if file_postfix in ['txt', 'sql']:
        filename_list_clean = filename_list[:-1]
        file_name = ''.join(filename_list_clean) + str(int(time.time() * 1000))
        file_name = format_file_name(file_name)
        # else:
        #     file_name = str(uuid.uuid1())
        sub_folder = time.strftime("%Y%m")
        upload_folder = os.path.join(config.MEDIA_ROOT, 'upload', sub_folder)
        if not os.path.exists(upload_folder):
            os.makedirs(upload_folder)
        absolute_path = os.path.join(upload_folder, file_name) + '.%s' % file_postfix
        if file_postfix.lower() in (
                "sql", "jpg", "jpeg", "bmp", "gif", "png", "xls", "xlsx", "rar", "doc", "docx", "zip", "pdf", "txt",
                "swf",
                "wmv"):
            destination = open(absolute_path, 'wb+')
            for chunk in file_obj.chunks():
                destination.write(chunk)
            destination.close()

            # if file_type == 'pic':  #暂不剪切图片
            #     if file_postfix.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png'):
            #         im = Image.open(absolute_path)
            #         im.thumbnail((720, 720))
            #         im.save(absolute_path)

            real_url = os.path.join('/media/', 'upload', sub_folder, file_name) + '.%s' % file_postfix
            response_dict = {'original': filename, 'url': real_url, 'title': 'source_file_tile', 'state': 'SUCCESS',
                             'msg': ''}
        else:
            response_dict = {'original': filename, 'url': '', 'title': 'source_file_tile', 'state': 'FAIL',
                             'msg': 'invalid file format'}
    else:
        response_dict = {'original': '', 'url': '', 'title': 'source_file_tile', 'state': 'FAIL',
                         'msg': 'invalid file obj'}
    return simplejson.dumps(response_dict)


def uploadfile(fileObj, file_type='pic'):
    """ 一个公用的上传文件的处理 """
    resp = ''
    if fileObj:
        filename = fileObj.name.decode('utf-8', 'ignore')
        fileExt = filename.split('.')[1]
        file_name = str(uuid.uuid1())
        subfolder = time.strftime("%Y%m")
        if not os.path.exists(config.MEDIA_ROOT[0] + subfolder):
            os.makedirs(config.MEDIA_ROOT[0] + subfolder)
        path = str(subfolder + '/' + file_name + '.' + fileExt)

        if fileExt.lower() in (
                'jpg', 'jpeg', 'bmp', 'gif', 'png', "rar", "doc", "docx", "zip", "pdf", "txt", "swf", "wmv"):

            phisypath = config.MEDIA_ROOT[0] + path
            destination = open(phisypath, 'wb+')
            for chunk in fileObj.chunks():
                destination.write(chunk)
            destination.close()

            if file_type == 'pic':
                if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png'):
                    im = Image.open(phisypath)
                    im.thumbnail((720, 720))
                    im.save(phisypath)

            real_url = '/static/upload/' + subfolder + '/' + file_name + '.' + fileExt
            resp = "{'original':'%s','url':'%s','title':'%s','state':'%s'}" % (
                filename, real_url, 'source_file_tile', 'SUCCESS')
    return resp


@csrf_exempt
def ueditor_index(request):
    action = request.GET.get('action', '')
    if action == 'config':
        setting = config.UEDITER_SETTING
        return HttpResponse(simplejson.dumps(setting), content_type='text/html; charset=utf-8',)
    elif action == 'uploadfile':
        return HttpResponse(ueditor_uploadfile(request))
    elif action == 'uploadimage':
        return HttpResponse(ueditor_uploadimage(request))
    else:
        return HttpResponseBadRequest()


def format_file_name(name):
    '''
    去掉名称中的url关键字
    '''
    URL_KEY_WORDS = ['#', '?', '/', '&', '.', '%']
    for key in URL_KEY_WORDS:
        name_list = name.split(key)
        name = ''.join(name_list)
    return name


def upload_file(file_obj, file_type='pic'):
    if file_obj:
        filename = file_obj.name
        # filename = file_obj.name.decode('utf-8', 'ignore')
        filename_list = filename.split('.')
        file_postfix = filename_list[-1]  # 后缀
        # if file_postfix in ['txt', 'sql']:
        filename_list_clean = filename_list[:-1]
        file_name = ''.join(filename_list_clean) + str(int(time.time() * 1000))
        file_name = format_file_name(file_name)
        # else:
        #     file_name = str(uuid.uuid1())
        sub_folder = time.strftime("%Y%m")
        upload_folder = os.path.join(config.MEDIA_ROOT, 'upload', sub_folder)
        if not os.path.exists(upload_folder):
            os.makedirs(upload_folder)
        absolute_path = os.path.join(upload_folder, file_name) + '.%s' % file_postfix
        if file_postfix.lower() in (
                "sql", "jpg", "jpeg", "bmp", "gif", "png", "xls", "xlsx", "rar", "doc", "docx", "zip", "pdf", "txt",
                "swf",
                "wmv"):
            destination = open(absolute_path, 'wb+')
            for chunk in file_obj.chunks():
                destination.write(chunk)
            destination.close()

            # if file_type == 'pic':  #暂不剪切图片
            #     if file_postfix.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png'):
            #         im = Image.open(absolute_path)
            #         im.thumbnail((720, 720))
            #         im.save(absolute_path)

            real_url = os.path.join('/media/', 'upload', sub_folder, file_name) + '.%s' % file_postfix
            response_dict = {'original': filename, 'url': real_url, 'title': 'source_file_tile', 'state': 'SUCCESS',
                             'msg': ''}
        else:
            response_dict = {'original': filename, 'url': '', 'title': 'source_file_tile', 'state': 'FAIL',
                             'msg': 'invalid file format'}
    else:
        response_dict = {'original': '', 'url': '', 'title': 'source_file_tile', 'state': 'FAIL',
                         'msg': 'invalid file obj'}
    return simplejson.dumps(response_dict)


@csrf_exempt
def ueditor_uploadimage(request):
    """
    上传图片
    :param request:
    :return:
    """
    fileObj = request.FILES.get('upfile', None)
    response = upload_file(fileObj, 'pic')
    return HttpResponse(response)


@csrf_exempt
def ueditor_uploadfile(request):
    """ 上传文件 """
    fileObj = request.FILES.get('upfile', None)
    response = upload_file(fileObj, 'file')
    return HttpResponse(response)
